import { getRepoCommits } from '@/apis/repo';
import { defineStore } from 'pinia';
import { repoActions, RepoCommitsType, repoGetters, repoState } from './types';

const state = (): repoState => {
    return {
        repoCommits: []
    }
}

const actions: repoActions = {
    async getAndSetRepoCommits(page: number) {
        const res = await getRepoCommits(page);
        res.data.forEach((item: any) => this.repoCommits.push(cleanCommitData(item)));
    }
}

const getters: repoGetters = {
    getCommits(state: repoState) {
        return state.repoCommits.reverse();
    }
}

function cleanCommitData(commitData: any) {
    const o: RepoCommitsType = {
        id: commitData.sha,
        url: commitData.html_url,
        avatar: commitData.author.name,
        avatarUrl: commitData.author.avatar_url,
        message: commitData.commit.message,
        date: commitData.commit.author.date,
    };
    return o;
}

export const useRepoStore = defineStore('repo', {
    state,
    actions,
    getters,
});

